import requests
import json
from tts import tts, open_config, initialize
import time
import socket
# from paddlespeech.s2t.frontend.audio import AudioSegment
from paddlespeech.server.bin.paddlespeech_client import ASROnlineClientExecutor

fastspeech2_config = "download/fastspeech2_nosil_baker_ckpt_0.4/default.yaml"
fastspeech2_checkpoint = "download/fastspeech2_nosil_baker_ckpt_0.4/snapshot_iter_76000.pdz"
fastspeech2_stat = "download/fastspeech2_nosil_baker_ckpt_0.4/speech_stats.npy"
pwg_config = "download/pwg_baker_ckpt_0.4/pwg_default.yaml"
pwg_checkpoint = "download/pwg_baker_ckpt_0.4/pwg_snapshot_iter_400000.pdz"
pwg_stat = "download/pwg_baker_ckpt_0.4/pwg_stats.npy"
phones_dict = "download/fastspeech2_nosil_baker_ckpt_0.4/phone_id_map.txt"
audio_path = "./in.wav"

# 初始化tts模型
fastspeech2_config, pwg_config = open_config(fastspeech2_config, pwg_config)
frontend, fastspeech2_inference, pwg_inference = initialize(phones_dict, fastspeech2_config, fastspeech2_checkpoint, fastspeech2_stat, pwg_config, pwg_checkpoint, pwg_stat)
asrclient_executor = ASROnlineClientExecutor()

# udp 服务
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 8091))
sock.settimeout(4)  

address = ('127.0.0.1', 7777)

while True:
    try:
        data, _ = sock.recvfrom(4096)
        if not data:
            continue
        data = data.decode('utf-8')
        print(data)
        parsed_data = json.loads(data)
        audio_path = parsed_data['path']
        
        print("接收完毕")
        print(data)

        # 语音识别
        res = asrclient_executor(
            input=audio_path,
            server_ip="127.0.0.1",
            port=8090,
            sample_rate=16000,
            lang="zh_cn",
            audio_format="wav")

        # res = '你的名字是什么'
        # res = "语言是人类进行沟通交流的表达方式，其储存着丰富的文化信息，传承着民族血脉，也支撑着文明的发展与演进。然而，一些少数民族语言、方言却正在无声无息地消失，与之密切相连的地域文化、历史文化也正面临濒危风险。“大约平均两周就会有一种语言消亡”，联合国教科文组织的这一调查数据让人触目惊心，且世界上正在使用的约6,000种语言，至少有43%面临濒危。而在中国，也有25种语言使用人口已不足千人。"


        # 撞词库
        zhuangci_headers = {'Content-Type': 'text/plain', 'Content-Length': str(len(res)*3), 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'charset': 'utf-8'}
        zhuangci_url = "http://127.0.0.1:8080/input"
        postres = requests.post(zhuangci_url, data=res.encode("utf-8"), headers=zhuangci_headers)
        rcv = postres.json()

        glm_url = "http://10.23.102.55:7861/chat"    #新的叫做8000  老的7861/chat
        history = []

        output = {}
        # 未匹配到撞词库
        if not bool(rcv):
            print("脑子了")
            data = {"question": "二十个字以内回答："+res, "history": history}   #老的叫做question  新的叫做prompt
            chatres = requests.post(glm_url, json=data).json()
            # history = chatres["history"]

            print(chatres["response"])  #新的叫做response  老的叫做 森么？
            tts(chatres["response"], frontend, fastspeech2_inference, pwg_inference, sock, address)
        elif rcv["type"] == "voice":
            print(rcv["回复"])
            tts(rcv["回复"], frontend, fastspeech2_inference, pwg_inference, sock, address)

        else:
            output = rcv
            output["type"] = "skill"
            output = str(output)
            sock.sendto(output.encode('utf-8'), address)

        print("完成")
        #time.sleep(1000)
        
    except KeyboardInterrupt:
        break
    except socket.timeout:
        continue
    #except socket.error:
    #    print("socket 异常")
    except Exception as e:
        output = {"type": "error"}
        sock.sendto(str(output).encode('utf-8'), address)
        print("错误处理", e)

sock.close()

